package com.example.mydy.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.mydy.R;
import com.example.mydy.model.RewardTask;
import com.example.mydy.utils.ImageLoader;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 我的悬赏任务列表适配器
 */
public class MyRewardAdapter extends RecyclerView.Adapter<MyRewardAdapter.ViewHolder> {

    private List<RewardTask> rewardTasks;
    private OnMyRewardClickListener listener;

    public interface OnMyRewardClickListener {
        void onRewardClick(RewardTask rewardTask);
        void onSubmitClick(RewardTask rewardTask);
        void onCancelClick(RewardTask rewardTask);
    }

    public MyRewardAdapter(List<RewardTask> rewardTasks, OnMyRewardClickListener listener) {
        this.rewardTasks = rewardTasks;
        this.listener = listener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_my_reward, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        RewardTask task = rewardTasks.get(position);
        
        // 设置任务标题和描述
        holder.titleTextView.setText(task.getTitle());
        holder.descriptionTextView.setText(task.getDescription());
        
        // 设置奖励金额
        holder.rewardAmountTextView.setText(String.format(Locale.getDefault(), "￥%.2f", task.getReward()));
        
        // 加载任务图片
        if (task.getImageUrl() != null && !task.getImageUrl().isEmpty()) {
            holder.taskImageView.setVisibility(View.VISIBLE);
            ImageLoader.loadImage(holder.itemView.getContext(), task.getImageUrl(), holder.taskImageView);
        } else {
            holder.taskImageView.setVisibility(View.GONE);
        }
        
        // 设置截止日期相关信息
        if (task.getDeadline() != null && !task.getDeadline().isEmpty()) {
            Date deadlineDate = task.getDeadlineAsDate();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
            holder.deadlineTextView.setText(String.format("截止日期: %s", sdf.format(deadlineDate)));
            
            // 计算剩余天数
            int daysLeft = getDaysLeft(deadlineDate);
            if (daysLeft > 0) {
                holder.daysLeftTextView.setVisibility(View.VISIBLE);
                holder.daysLeftTextView.setText(String.format("剩余%d天", daysLeft));
                
                // 根据剩余天数设置颜色
                if (daysLeft <= 3) {
                    holder.daysLeftTextView.setTextColor(holder.itemView.getContext().getResources().getColor(R.color.colorError));
                } else {
                    holder.daysLeftTextView.setTextColor(holder.itemView.getContext().getResources().getColor(R.color.colorPrimary));
                }
            } else {
                holder.daysLeftTextView.setVisibility(View.GONE);
            }
        } else {
            holder.deadlineTextView.setText("长期任务");
            holder.daysLeftTextView.setVisibility(View.GONE);
        }
        
        // 根据任务状态设置不同的视觉效果和功能
        updateViewByStatus(holder, task);
        
        // 设置点击事件
        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onRewardClick(task);
            }
        });
        
        // 根据状态设置操作按钮
        setupActionButtons(holder, task);
    }

    /**
     * 根据任务状态更新视图
     */
    private void updateViewByStatus(ViewHolder holder, RewardTask task) {
        int progressStatus = task.getProgressStatus();
        Context context = holder.itemView.getContext();
        
        switch (progressStatus) {
            case RewardTask.STATUS_IN_PROGRESS:
                // 进行中状态
                holder.statusTextView.setText("进行中");
                holder.statusTextView.setTextColor(context.getResources().getColor(R.color.colorInProgress));
                
                holder.progressBar.setVisibility(View.VISIBLE);
                holder.progressBar.setProgress(30); // 示例进度
                
                // 显示提交按钮，隐藏取消按钮
                holder.submitButton.setVisibility(View.VISIBLE);
                holder.cancelButton.setVisibility(View.VISIBLE);
                break;
                
            case RewardTask.STATUS_UNDER_REVIEW:
                // 审核中状态
                holder.statusTextView.setText("审核中");
                holder.statusTextView.setTextColor(context.getResources().getColor(R.color.colorUnderReview));
                
                holder.progressBar.setVisibility(View.VISIBLE);
                holder.progressBar.setProgress(75); // 示例进度
                
                // 隐藏提交按钮，隐藏取消按钮
                holder.submitButton.setVisibility(View.GONE);
                holder.cancelButton.setVisibility(View.GONE);
                break;
                
            case RewardTask.STATUS_COMPLETED:
                // 已完成状态
                holder.statusTextView.setText("已完成");
                holder.statusTextView.setTextColor(context.getResources().getColor(R.color.colorCompleted));
                
                holder.progressBar.setVisibility(View.VISIBLE);
                holder.progressBar.setProgress(100); // 完成进度
                
                // 隐藏提交按钮，隐藏取消按钮
                holder.submitButton.setVisibility(View.GONE);
                holder.cancelButton.setVisibility(View.GONE);
                break;
                
            case RewardTask.STATUS_REJECTED:
                // 已拒绝状态
                holder.statusTextView.setText("已拒绝");
                holder.statusTextView.setTextColor(context.getResources().getColor(R.color.colorRejected));
                
                holder.progressBar.setVisibility(View.VISIBLE);
                holder.progressBar.setProgress(50); // 示例进度
                
                // 显示重新提交按钮，隐藏取消按钮
                holder.submitButton.setVisibility(View.VISIBLE);
                holder.submitButton.setText("重新提交");
                holder.cancelButton.setVisibility(View.GONE);
                break;
                
            default:
                // 默认状态
                holder.statusTextView.setText("未知状态");
                holder.statusTextView.setTextColor(context.getResources().getColor(R.color.colorText));
                
                holder.progressBar.setVisibility(View.GONE);
                
                // 隐藏所有按钮
                holder.submitButton.setVisibility(View.GONE);
                holder.cancelButton.setVisibility(View.GONE);
                break;
        }
    }

    /**
     * 设置操作按钮
     */
    private void setupActionButtons(ViewHolder holder, RewardTask task) {
        // 提交按钮
        holder.submitButton.setOnClickListener(v -> {
            if (listener != null) {
                listener.onSubmitClick(task);
            }
        });
        
        // 取消按钮
        holder.cancelButton.setOnClickListener(v -> {
            if (listener != null) {
                listener.onCancelClick(task);
            }
        });
    }

    @Override
    public int getItemCount() {
        return rewardTasks.size();
    }
    
    /**
     * 更新数据
     */
    public void updateData(List<RewardTask> newData) {
        this.rewardTasks = newData;
        notifyDataSetChanged();
    }
    
    /**
     * 计算截止日期还剩多少天
     */
    private int getDaysLeft(Date deadlineDate) {
        Calendar today = Calendar.getInstance();
        today.set(Calendar.HOUR_OF_DAY, 0);
        today.set(Calendar.MINUTE, 0);
        today.set(Calendar.SECOND, 0);
        today.set(Calendar.MILLISECOND, 0);
        
        Calendar deadline = Calendar.getInstance();
        deadline.setTime(deadlineDate);
        deadline.set(Calendar.HOUR_OF_DAY, 0);
        deadline.set(Calendar.MINUTE, 0);
        deadline.set(Calendar.SECOND, 0);
        deadline.set(Calendar.MILLISECOND, 0);
        
        long diff = deadline.getTimeInMillis() - today.getTimeInMillis();
        return (int) (diff / (24 * 60 * 60 * 1000));
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView titleTextView;
        TextView descriptionTextView;
        TextView rewardAmountTextView;
        TextView deadlineTextView;
        TextView daysLeftTextView;
        TextView statusTextView;
        ImageView taskImageView;
        ProgressBar progressBar;
        Button submitButton;
        Button cancelButton;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            titleTextView = itemView.findViewById(R.id.tv_task_title);
            descriptionTextView = itemView.findViewById(R.id.tv_task_description);
            rewardAmountTextView = itemView.findViewById(R.id.tv_reward_amount);
            deadlineTextView = itemView.findViewById(R.id.tv_deadline);
            daysLeftTextView = itemView.findViewById(R.id.tv_days_left);
            statusTextView = itemView.findViewById(R.id.tv_status);
            taskImageView = itemView.findViewById(R.id.iv_task_image);
            progressBar = itemView.findViewById(R.id.progress_bar);
            submitButton = itemView.findViewById(R.id.btn_submit);
            cancelButton = itemView.findViewById(R.id.btn_cancel);
        }
    }
} 